//
//  TranProductView.swift
//  ptbuy
//
//  Created by MyMac on 2024/12/6.
//

import SwiftUI
import CoreData
import AVFoundation
import AVKit
/*
 查看商品页面
 */
struct TranProductView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    
    @ObservedObject var modigyClient:Client
    @Binding var tranProduct:Bool
    
    @State private var isScreen:Bool = false//筛选框
    @State var screenProductName:String = ""//筛选
    
    @State var beginTime:String = "请选择开始时间"//筛选
    @State var endTime:String = "请选择结束时间"//筛选
    
    @State var screenBeginTime = Date()//筛选
    @State private var showDatePicker = false  // 控制日期选择器是否显示
    
    @State var screenEndTime = Date()//筛选
    @State private var showDatePickerEnd = false  // 控制日期选择器是否显示
    
   
    @State var clientName:String = ""//
    @State var clientId:String = ""//
    @State var productPrice:Int64 = 0//修改的商品价格
    
    @State private var totalProduct:Int16 = 0 //显示总商品件数
    @State private var totalPrice:Int64 = 0//显示商品总价格
    @State private var maxOrder:Int16 = 0//商品最大排序
    
    @State private var removeStatus:Bool = false//删除状态提示
    
    @State private var modifyStatus:Bool = false//修改状态提示
    
    
    @State private var mediaStatus:Bool = false//照片状态提示
    @State private var mediaStatusSuccess:Bool = false//照片修改状态提示
    
    @State private var isImagePresented = false//点击图片全屏显示
    @State private var isFullScreen = false//点击视频全屏显示
    
    @State private var products:[Product] = []
    
    @State private var productIdEdit:String = ""
    @State private var productNameEdit:String = ""
    @State private var productPriceEdit:Int64 = 0
    
    @State private var addProduct:Bool = false
    @State private var addProductStatus:Bool = false
    
    
    
    var body: some View {
        NavigationView {
            VStack{
                Divider()
                if isScreen{
                    VStack{
                        HStack{
                            Text("名    称:") .font(.system(size: 15))
                            Spacer()
                            TextField("名    称",text: $screenProductName).minimumScaleFactor(0.3)
                                .multilineTextAlignment(.center)
                                .minimumScaleFactor(0.3).overlay(
                                    Rectangle()
                                        .frame(height: 1)
                                        .foregroundColor(Color.black)
                                        .padding([.top])
                                )
                                .cornerRadius(8).font(.system(size: 15))
                        }.padding([.leading,.trailing],30)
                        Divider()
                        HStack{
                            Text("开始时间:") .font(.system(size: 15))
                            Spacer()
                            // 显示当前选中的日期
                            Text(beginTime).frame(maxWidth:.infinity)
                               .padding()
                                .multilineTextAlignment(.center)
                                .minimumScaleFactor(0.3).overlay(
                                    RoundedRectangle(cornerRadius: 8)
                                    .stroke(Color.black,lineWidth: 0.5) // 设置边框
                                ).edgesIgnoringSafeArea(.all) // 忽略安全区域，使视图覆盖整个屏幕
                                .cornerRadius(8) // 设置最大宽高为无穷，确保视图覆盖全屏
                                .onTapGesture {
                                    showDatePicker.toggle()  // 显示日期选择器
                                }
                                .cornerRadius(8).font(.system(size: 15))
                      
                        }.padding([.leading,.trailing],30)
                        Divider()
                        HStack{
                            Text("结束时间:") .font(.system(size: 15))
                            Spacer()
                            // 显示当前选中的日期
                            Text(endTime).frame(maxWidth:.infinity)
                               .padding()
                                .multilineTextAlignment(.center)
                                .minimumScaleFactor(0.3).overlay(
                                    RoundedRectangle(cornerRadius: 8)
                                    .stroke(Color.black,lineWidth: 0.5) // 设置边框
                                ).edgesIgnoringSafeArea(.all) // 忽略安全区域，使视图覆盖整个屏幕
                                .cornerRadius(8) // 设置最大宽高为无穷，确保视图覆盖全屏
                                .onTapGesture {
                                    showDatePickerEnd.toggle()  // 显示日期选择器
                                }
                                .cornerRadius(8).font(.system(size: 15))
                      
                        }.padding([.leading,.trailing],30)
                        Divider()
                        HStack {
                                Button(action:{
                                    isScreen = false
                                    screenProductName = ""
                                    beginTime = "请选择开始时间"
                                    endTime = "请选择结束时间"
                                    
                                    searchProduct()
                                }) {
                                    Text("不筛选").padding().frame(maxWidth: .infinity,maxHeight:30,alignment: .center)
                                }.overlay(
                                    RoundedRectangle(cornerRadius: 8)
                                    .stroke(Color.black,lineWidth: 0.5) // 设置边框
                                ).edgesIgnoringSafeArea(.all) // 忽略安全区域，使视图覆盖整个屏幕
                                .cornerRadius(8) // 设置最大宽高为无穷，确保视图覆盖全屏
                                        
                                Button(action:{
                                    searchProduct()
                                }) {
                                    Text("查询").padding().frame(maxWidth: .infinity,maxHeight:30,alignment: .center)
                                }
                                .overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.black,lineWidth: 0.5) // 设置边框
                                ).edgesIgnoringSafeArea(.all) // 忽略安全区域，使视图覆盖整个屏幕
                                .cornerRadius(8) // 设置最大宽高为无穷，确保视图覆盖全屏
                                        
                            }.padding([.leading,.trailing],30)
                    }
                    .sheet(isPresented: $showDatePicker) {
                        DatePickerView(screenTime: $screenBeginTime, isPresented: $showDatePicker,stringTime:$beginTime)
                    }.sheet(isPresented: $showDatePickerEnd) {
                        DatePickerView(screenTime: $screenEndTime, isPresented: $showDatePickerEnd,stringTime:$endTime)
                    }
                    Divider()
                }
               
                ScrollView {
                    VStack() {
                        ForEach(products) { item in
                            VStack{
                                HStack(){
                                    if let mult = item.mult,!mult.isEmpty{
                                        let strAndJson:[String] = Utils.convertJsonStringToArray(
                                            jsonString: mult
                                        )
                                        if strAndJson.count>0{
                                            if(strAndJson[0].contains(".mov") || strAndJson[0].contains(".MOV")){
                                                let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                                    strAndJson[0]
                                                )
                                                let player = AVPlayer(url: URL(fileURLWithPath: filename.path))
                                                VideoPlayer(player: player).frame(
                                                        width:70,
                                                        height: 120,
                                                        alignment: .center
                                                    ).padding(8).onTapGesture {// 点击时，进入全屏模式
                                                        isFullScreen.toggle()
                                                    }.onAppear {// 在视图显示时播放视频
                                                        player.pause()
                                                    }.fullScreenCover(isPresented: $isFullScreen) {
                                                        // 全屏播放视频
                                                        VideoPlayer(player: player).edgesIgnoringSafeArea(.all) // 使视频全屏
                                                        .onTapGesture() {// 点击时，进入全屏模式
                                                            isFullScreen.toggle()}.onAppear {// 在视图显示时播放视频
                                                            player.play()
                                                        }
                                                    }
                                            }else{
                                                let filename = Utils.getDocumentsDirectory().appendingPathComponent(strAndJson[0])
                                                if let uiImage = UIImage(contentsOfFile: filename.path) {
                                                    Image(uiImage:uiImage).resizable()  // 使图片可以调整大小
                                                        .scaledToFit() // 保持图片比例，适应容器的宽高
                                                        .frame(width:70,height: 120,alignment: .center).padding(8)
                                                }else{
                                                    Image("no_image").resizable()  // 使图片可以调整大小
                                                        .scaledToFit() // 保持图片比例，适应容器的宽高
                                                        .frame(width:70,height: 120,alignment: .center).padding(8)
                                                }
                                            }
                                        }
                                    }else{
                                        Image("no_image")
                                            .resizable()  // 使图片可以调整大小
                                            .scaledToFit() // 保持图片比例，适应容器的宽高
                                            .frame(
                                                width:70,
                                                height: 120,
                                                alignment: .center
                                            ).padding(8)
                                    }
                                    VStack{
                                        HStack{
                                            Text("  编    号 ：").font(.system(size: 15)).frame(height:15).multilineTextAlignment(.leading).padding([.top,.bottom],5)
                                            Spacer()
                                            Text(String(item.myorder)).font(.system(size: 15))
                                        }.frame(height:15).padding([.top,.trailing],10)
                                        
                                        Divider().background(Color.gray.opacity(0.5))
                                        
                                        HStack{
                                            Text("  名    称 ：").frame(height:15).font(.system(size: 15)).multilineTextAlignment(.leading).padding([.top,.bottom],5)
                                            Spacer()
                                            Text("")
                                        }
                                        
                                        VStack{
                                            Divider()
                                            Text(item.product_name ?? "").minimumScaleFactor(0.3).frame(height:50).edgesIgnoringSafeArea(.all) // 忽略安全区域，使视图覆盖整个屏幕
                                        }.font(.system(size: 15))
                                        
                                        Divider().background(Color.gray.opacity(0.5))
                                        
                                        HStack{
                                            Text("  价    格 ：").font(.system(size: 15)).frame(height:15).multilineTextAlignment(.leading)
                                            Spacer()
                                            Text("\(item.product_price)元").font(.system(size: 15))
                                            
                                        }
                                        
                                        Divider().background(Color.gray.opacity(0.5))
                                        
                                        HStack{
                                            Text("  记录时间 ：").font(.system(size: 15)).frame(height:15).multilineTextAlignment(.leading).padding([.top,.bottom],5)
                                            Spacer()
                                            Text(item.time ?? "").font(.system(size: 15)).minimumScaleFactor(0.3).frame(height:15)
                                        }
                                    }
                                    .frame(maxWidth: .infinity,minHeight: 150,alignment: .leading)
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 0)
                                            .stroke(
                                                Color.black,
                                                lineWidth: 0.5
                                            ) // 设置边框
                                    ).edgesIgnoringSafeArea(
                                        .all
                                    ) // 忽略安全区域，使视图覆盖整个屏幕
                                    .cornerRadius(0)
                                }.frame(
                                    maxWidth: .infinity,
                                    alignment: .leading
                                )
                                .overlay(
                                    RoundedRectangle(cornerRadius: 1)
                                        .stroke(
                                            Color.black,
                                            lineWidth: 0.5
                                        ) // 设置边框
                                ).edgesIgnoringSafeArea(
                                    .all
                                ) // 忽略安全区域，使视图覆盖整个屏幕
                                .cornerRadius(1) // 设置最大宽高为无穷，确保视图覆盖全屏
                                
                            
                                HStack{
                                    Button(action:{
                                        removeStatus = true
                                    }){
                                        Text("删除")
                                    }.buttonStyle(
                                        MyButtonStyle(width:80,size:15,height: .infinity)
                                    ).alert("是否删除此商品？",isPresented:$removeStatus){
                                        Button("取消",role:.cancel){
                                            removeStatus = false
                                        }
                                        Button("删除",role:.destructive){
                                            removeProduct(item:item)
                                            removeStatus = false
                                        }
                                    }
                                    Spacer()
                                    Button(action:{
                                        mediaStatus = true
                                        if let id = item.id{
                                            productIdEdit = id
                                        }
                                    }){
                                        Text("照片")
                                    }.alert("修改失败",isPresented:$mediaStatusSuccess){
                                        Button("关闭", role: .cancel) {
                                            mediaStatusSuccess = false
                                        }
                                    }.buttonStyle(
                                        MyButtonStyle(width:80,size:15,height: .infinity)
                                    )
                                    Spacer()
                                    Button(action:{
                                        productPriceEdit = Int64(item.product_price)
                                        if let name = item.product_name{
                                            productNameEdit = name
                                        }
                                        
                                        if let id = item.id{
                                            productIdEdit = id
                                        }
                                        withAnimation {
                                            modifyStatus.toggle()
                                        }
                                    }){
                                        Text("修改")
                                    }
                                    .alert("修改失败",isPresented:$mediaStatusSuccess){
                                        Button("关闭", role: .cancel) {
                                            mediaStatusSuccess = false
                                        }
                                    }
                                    .buttonStyle(
                                        MyButtonStyle(width:80,size:15,height: .infinity)
                                    )
                                }.padding()
                                
                                
                                
                            }.frame(maxWidth:.infinity)
                                .background(Color("endColor"))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(
                                            Color.black,
                                            lineWidth: 0.5
                                        ) // 设置边框
                                ).edgesIgnoringSafeArea(
                                    .all
                                ) // 忽略安全区域，使视图覆盖整个屏幕
                                .cornerRadius(10) // 设置最大宽高为无穷，确保视图覆盖全屏
                                .padding([.leading,.trailing])
                        }
                    }.padding([.top,.bottom])
                        
            }.simultaneousGesture(DragGesture()) // 允许内外层同时滚动
                
                Divider()
                HStack{
                    Spacer()
                    Text("总件数：\(totalProduct)件")
                    Spacer()
                    Text("总价：\(totalPrice)元")
                    Spacer()
                }.padding(8)
                
            }.onAppear{
                if let  id = modigyClient.id{
                    clientId = id
                 
                    fetchPriduct(predicate:NSPredicate(format: "pid = %@",clientId))
                    
                }
                if let  name = modigyClient.name{
                    clientName = name
                }
                mathSum()
            }.overlay(
                modifyStatus ? modifyProductOverlayView : nil
            ).onChange(of: mediaStatus){ newValue in
                // 当属性改变时执行某些操作
                if !newValue{
                    fetchPriduct(predicate:NSPredicate(format: "pid = %@",clientId))
                }
            }.onChange(of: addProduct){ newValue in
                // 当属性改变时执行某些操作
                if !newValue{
                    fetchPriduct(predicate:NSPredicate(format: "pid = %@",clientId))
                }
            }.fullScreenCover(isPresented: $mediaStatus){
                ProductMediaView(mediaStatus:$mediaStatus,productId:$productIdEdit,mediaStatusSuccess:$mediaStatusSuccess)
            }.fullScreenCover(isPresented: $addProduct){
                ProductAddView(addProduct:$addProduct,clientId:$clientId,addProductStatus:$addProductStatus,
                               totalProduct:$totalProduct,totalPrice:$totalPrice,maxOrder:$maxOrder)
            }.frame(maxWidth:.infinity,maxHeight: .infinity).background(
                // 创建渐变背景
                LinearGradient(
                    gradient: Gradient(
                        colors: [
                            Color("startColor").opacity(
                                10
                            ),
                            // 上半部分颜色，增加不透明度
                            Color("endColor").opacity(0.1)
                        ]// 上半部分颜色，增加不透明度
                    ),
                    startPoint: .top,
                    endPoint: .bottom
                )
                .edgesIgnoringSafeArea(.all)  // 确保背景覆盖整个屏幕
            ).navigationBarTitle("[\(clientName)]商品信息", displayMode: .inline) // 设置导航栏标题
                .navigationViewStyle(
                    StackNavigationViewStyle()
                ) // 推荐在全屏时使用此样式
                .background()
                .toolbar {
                    // 修改标题字体大小
                    ToolbarItem(placement: .topBarLeading) {
//                        Text("返回").font(.system(size: 18))
//                            .clipShape(
//                                Capsule()
//                            ) // 使用 Capsule 形状来实现圆角效果
//                            .onTapGesture {
//                                tranProduct = false
//                            }
                        Button(action: {       // 自定义返回动作
                            tranProduct = false
                            }) {
                                Image(systemName: "arrow.left.circle.fill") // 返回图标
                            }
                    }
                    ToolbarItem(placement: .navigationBarTrailing) {
                        // 使用 toolbarTitleMenu 创建下拉菜单
                        Menu {
                            Button("筛选") {
                                isScreen = true
                            }
                            Button(action:{
                                withAnimation {
                                    addProduct.toggle()
                                }
                            }){
                                Text("新增商品")
                            }.alert("新增商品失败",isPresented:$addProductStatus){
                                Button("关闭", role: .cancel) {
                                    addProductStatus = false
                                }
                            }
                        } label: {
                            // 设置菜单的图标
                            Image(systemName: "ellipsis").imageScale(.large)
                        }
                    }
                }
        }.navigationBarBackButtonHidden(true)
    }
    
    

    /*
     手动查询，，新增，删除、修改后都需要调用这个方法
     直接调用这个就可以了
     fetchPriduct(predicate:NSPredicate(format: "pid = %@",clientId))
     */
    func fetchPriduct(predicate:NSPredicate){
        let fetchRequest: NSFetchRequest<Product> = Product.fetchRequest()
        fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Product.myorder, ascending: false)]
        fetchRequest.predicate = predicate
       do {
           products = try viewContext.fetch(fetchRequest) // 执行查询并获取数据
           
          let order = products.max(by: { $0.myorder < $1.myorder })?.myorder
           maxOrder = Int16(order ?? 0)
           
       } catch {
           print("Failed to fetch items: \(error)")
       }
    }
    
    
    func mathSum(){
        totalProduct = Int16(products.count)
        
        totalPrice = products.map(\.product_price).reduce(0,+)
      }
    
    
    //筛选查询
    func searchProduct(){
        
        
        var nsPredicateArr:[NSPredicate] = []
        
        
        let id: NSPredicate
        if !clientId.isEmpty{
            id = NSPredicate(
                format: "pid = %@",
                clientId
            )  // 模糊查询
            nsPredicateArr.append(id)
        }
        
        let predicateName: NSPredicate
        if !screenProductName.isEmpty{
            predicateName = NSPredicate(
                format: "product_name = %@",
                screenProductName
            )  // 模糊查询
            nsPredicateArr.append(predicateName)
        }
        
        let bTime: NSPredicate
        if !beginTime.isEmpty && beginTime != "请选择开始时间"{
            let time = beginTime.replacingOccurrences(of: "-", with: "")
            bTime = NSPredicate(
                format: "inttime >= %@",
                argumentArray: [Int64(time) ?? 0]
            )  // 模糊查询
            nsPredicateArr.append(bTime)
        }
        let eTime: NSPredicate
        if !endTime.isEmpty && endTime != "请选择结束时间"{
            let _time = endTime.replacingOccurrences(of: "-", with: "")
            eTime = NSPredicate(
                format: "inttime <= %@",
                argumentArray: [Int64(_time) ?? 0]
            )  // 模糊查询
            nsPredicateArr.append(eTime)
        }
        let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: nsPredicateArr)
      
//        products.nsPredicate = predicate
        
        fetchPriduct(predicate:predicate)
        
    }
    // 用于格式化日期的日期格式器
    private var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter
    }
    
    
    //修改客户信息
   func modifyClient(){
       modigyClient.total_price = products.map(\.product_price).reduce(0,+)
       modigyClient.total_product = Int16(products.count)
       do{
           try viewContext.save()
       }catch{
           print("error update client data")
       }
   }
    /*
      ----------------新增商品信息，已经测试通过----------------
     */
    
    /*
      删除商品信息
     */
    private func removeProduct(item:Product){
        viewContext.delete(item)
        do {
            try viewContext.save()
            fetchPriduct(predicate:NSPredicate(format: "pid = %@",clientId))
            modifyClient()
            mathSum()
        } catch {
            print("Failed to delete item: \(error.localizedDescription)")
        }
    }
    
    /*
     修改商品信息
     */
    private func modifyProduct(){
        // 查找对应的 Product
        let fetchRequest: NSFetchRequest<Product> = Product.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "id == %@", productIdEdit)
        
        do {
            let results = try viewContext.fetch(fetchRequest)

            if let product = results.first {
                // 更新该 person 的名字
                product.product_name = productNameEdit
                product.product_price = productPriceEdit
                try viewContext.save()  // 保存更新
                modifyClient()
                mathSum()
            }
        } catch {
            print("更新失败：\(error.localizedDescription)")
        }
    }
    
    
    var modifyProductOverlayView: some View {
        VStack {
            Spacer()
            VStack{
                Text("修改")
                    .font(.headline)
                    .padding()
       
                Form {
                    Section(header: Text("")) {
                        HStack{
                            Text("名称：")
                            TextField(
                                "名称",
                                text: $productNameEdit
                            ).minimumScaleFactor(0.3)
                                .textFieldStyle(
                                    RoundedBorderTextFieldStyle()
                                )
                           
                        }.padding([.top,.bottom],8)
                        
                        HStack{
                            Text("价格：")
                            TextField(
                                "价格",
                                value: $productPriceEdit,format:.number
                            ).keyboardType(.numberPad)
                                .textFieldStyle(
                                    RoundedBorderTextFieldStyle()
                                )
                               
                        }.padding([.top,.bottom],8)
                        
                    }
                    
                }.frame(height: 200)  // 使 Form 自适应内容高度
                HStack {
                    Button(action:{
                        modifyStatus = false
                    }) {
                        Text("取消").padding().frame(
                            maxWidth: .infinity,
                            alignment: .center
                        )
                    }
                    .overlay(
                        RoundedRectangle(
                            cornerRadius: 8
                        )
                        .stroke(
                            Color.black,
                            lineWidth: 0.5
                        ) // 设置边框
                    ).edgesIgnoringSafeArea(
                        .all
                    ) // 忽略安全区域，使视图覆盖整个屏幕
                    .cornerRadius(
                        8
                    ) // 设置最大宽高为无穷，确保视图覆盖全屏
                            
                    Button(action:{
                        // Handle form submission
                        modifyProduct()
                        modifyStatus = false
                    }) {
                        Text("确定").padding().frame(
                            maxWidth: .infinity,
                            alignment: .center
                        )
                           
                    }
                    .overlay(
                        RoundedRectangle(
                            cornerRadius: 8
                        )
                        .stroke(
                            Color.black,
                            lineWidth: 0.5
                        ) // 设置边框
                    ).edgesIgnoringSafeArea(
                        .all
                    ) // 忽略安全区域，使视图覆盖整个屏幕
                    .cornerRadius(
                        8
                    ) // 设置最大宽高为无穷，确保视图覆盖全屏
                            
                }
            }.frame(maxWidth: .infinity, minHeight: 200)
                .background(Color.white)
                .cornerRadius(12)
                .shadow(radius: 8)
                .padding(.horizontal, 30)
                            
            Spacer()
        }.background(
            // 背景遮罩
            Color.black.opacity(0.5)
                .edgesIgnoringSafeArea(.all)
            
        )
    }
}
